import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from './utils/get-page-title'
import { asyncRoutes } from '@/router'
// 路由导航守卫
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // document.title = '人力资源管理系统-' + to.meta.title
  document.title = getPageTitle(to.meta.title)
  // console.log(to.path, to, '去哪里')
  // console.log(from.path, '从哪来')
  NProgress.start()
  const token = store.state.user.token
  // 存token
  if (token) {
    if (to.path === '/login') {
      console.log('已经登录不能回登录回首页')
      next('/')
      NProgress.done()
    } else {
      console.log('已经登录放行')
      store.dispatch('user/setUserInfo')
      if (!store.state.user.userInfo.userId) {
        const menus = await store.dispatch('user/setUserInfo')
        console.log(menus, 'menus')
        console.log(asyncRoutes, 'asyncRoutes')
        const filterRoutes = asyncRoutes.filter(item => {
          return menus.includes(item.children[0].name)
        })
        console.log(filterRoutes, 'filterRoutes')
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoutes)
        store.commit('menus/setmenusList', filterRoutes)
        // 白屏问题
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      console.log('白名单放行')
      next()
    } else {
      console.log('没有token和白名单返回登录')
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  NProgress.done()
})
